package com.newvpn.fastbest.zenith.presenter;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.google.android.gms.ads.AdError;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdLoader;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdValue;
import com.google.android.gms.ads.AdapterResponseInfo;
import com.google.android.gms.ads.FullScreenContentCallback;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.OnPaidEventListener;
import com.google.android.gms.ads.appopen.AppOpenAd;
import com.google.android.gms.ads.interstitial.InterstitialAd;
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback;
import com.google.android.gms.ads.nativead.NativeAd;
import com.google.android.gms.ads.nativead.NativeAdOptions;
import com.newvpn.fastbest.zenith.VPNApp;
import com.newvpn.fastbest.zenith.utils.AdConfigUtils;
import com.newvpn.fastbest.zenith.utils.AdSwith;
import com.newvpn.fastbest.zenith.utils.AdValueUpload;
import com.newvpn.fastbest.zenith.utils.VLog;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.disposables.Disposable;

public enum AdPresenter {
    INSTANCE;

    private AdConfigUtils mAdConfigUtils = new AdConfigUtils();

    private void preAllAd() {
        preAd(null);
        preNativeAd(null);
        preSplashAd(null);
    }

    public AdConfigUtils getAdConfigUtils() {
        return mAdConfigUtils;
    }

    public void preAd(PreAdCallback callback) {
        int status = VPNPresenter.INSTANCE.getVPNStatus();
        final boolean isConnected = status == VPNReulst.STATE_CONNECTED || status == VPNReulst.STATE_CONNECTED_PRE || status == VPNReulst.STATE_CONNECTED_LOADADING;
        String adId = isConnected ? mAdConfigUtils.afterAdID : mAdConfigUtils.beforeAdID;
        if (TextUtils.isEmpty(adId)) {
            if (callback != null) {
                callback.fail();
            }
            return;
        }
        VLog.e("preAd beign");
        AdRequest adRequest = new AdRequest.Builder().build();
        InterstitialAd.load(VPNApp.getBase(), adId, adRequest, new InterstitialAdLoadCallback() {
            @Override
            public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                super.onAdFailedToLoad(loadAdError);
                VLog.e("preAd onAdFailedToLoad：" + loadAdError);
                if (isConnected) {
                    mAdConfigUtils.afterAd = null;
                } else {
                    mAdConfigUtils.beforeAd = null;
                }
                if (callback != null) {
                    callback.fail();
                }

            }

            @Override
            public void onAdLoaded(@NonNull InterstitialAd interstitialAd) {
                super.onAdLoaded(interstitialAd);
                VLog.e("preAd onAdLoaded");
                if (isConnected) {
                    mAdConfigUtils.afterAd = interstitialAd;
                } else {
                    mAdConfigUtils.beforeAd = interstitialAd;
                }
                if (callback != null) {
                    callback.load(interstitialAd);
                }
            }
        });
    }

    Disposable loadADDisposable;

    public void loadAD(Activity activity, String scence, LoadAdCallback callback, long startTime, long waitTime) {
//        不进行广告等待
//        if (System.currentTimeMillis() - startTime > waitTime) {
//            if (callback != null) {
//                callback.endLoad(false);
//            }
//            VLog.e("loadAD outtime");
//            if (loadADDisposable != null) {
//                loadADDisposable.dispose();
//            }
//            return;
//        }
        int waitPreAdTime = 2 * 1000;
        int status = VPNPresenter.INSTANCE.getVPNStatus();
        final boolean isConnected = status == VPNReulst.STATE_CONNECTED || status == VPNReulst.STATE_CONNECTED_PRE || status == VPNReulst.STATE_CONNECTED_LOADADING;
        String adId = isConnected ? mAdConfigUtils.afterAdID : mAdConfigUtils.beforeAdID;
        if (TextUtils.isEmpty(adId)) {
            if (callback != null) {
                VLog.e("adId isEmpty");
                if (callback != null) {
                    callback.endLoad(false);
                }
                //callback.endLoad(false);
//                if (loadADDisposable != null) {
//                    loadADDisposable.dispose();
//                }
//                //隔1s再加载
//                loadADDisposable = Observable.timer(0, TimeUnit.MILLISECONDS) // 设置500ms的定时器
//                        .switchMap(aLong -> Observable.interval(1, TimeUnit.SECONDS))
//                        .observeOn(AndroidSchedulers.mainThread()) // 指定在主线程上执行
//                        .subscribe(
//                                aLong -> {
//                                    if (System.currentTimeMillis() - startTime > waitPreAdTime) {
//                                        return;
//                                    }
//                                    loadAD(activity, scence, callback, startTime, waitTime);
//                                },
//                                throwable -> {
//                                    loadADDisposable.dispose();
//                                },
//                                () -> {
//                                    loadADDisposable.dispose();
//                                }
//                        );
            }
            return;
        }
        InterstitialAd ad = isConnected ? mAdConfigUtils.afterAd : mAdConfigUtils.beforeAd;
        if (ad == null) {
            VLog.e("loadAD ad == null,preAd");

            preAd(new PreAdCallback() {
                @Override
                public void load(Object ad) {
//                    if (ad instanceof InterstitialAd) {
//                        VLog.e("showAd begin");
//                        showAd(activity, (InterstitialAd) ad, scence, callback);
//                    }
//                    if (callback != null) {
//                        callback.endLoad(true);
//                    }
                }

                @Override
                public void fail() {
                    VLog.e("preAd ad fail");
//                    if (callback != null) {
//                        callback.endLoad(false);
//                    }
                }
            });
            //2s后检测结果
            if (loadADDisposable != null) {
                loadADDisposable.dispose();
            }
            loadADDisposable = Observable.timer(2, TimeUnit.SECONDS)
                    .observeOn(AndroidSchedulers.mainThread()) // 指定在主线程上执行
                    .subscribe(
                            aLong -> {

                            },
                            throwable -> {
                                callback.endLoad(false);
                            },
                            () -> {
                                InterstitialAd interstitialAd = isConnected ? mAdConfigUtils.afterAd : mAdConfigUtils.beforeAd;
                                if (interstitialAd ==  null){
                                    callback.endLoad(false);
                                }else {
                                    callback.endLoad(true);
                                    showAd(activity, ad, scence, callback);
                                }
                                loadADDisposable.dispose();
                            }
                    );
            return;
        }
        showAd(activity, ad, scence, callback);
    }

    private void showAd(Activity activity, InterstitialAd ad, String scence, LoadAdCallback callback) {
        if (ad != null) {
            ad.show(activity);
            setAdPaidListener(ad, scence, UUID.randomUUID());
            VLog.e("showAd begin");
            ad.setFullScreenContentCallback(new FullScreenContentCallback() {
                @Override
                public void onAdClicked() {
                    super.onAdClicked();
                    Map<String, Object> map = new HashMap<>();
                    map.put("scene", scence);
                    VLog.event("Intersitial_Click", map);
                }

                @Override
                public void onAdDismissedFullScreenContent() {
                    super.onAdDismissedFullScreenContent();
                    //VPNApp.setInApp(true);
                    mAdConfigUtils.afterAd = null;
                    mAdConfigUtils.beforeAd = null;
                    preAd(null);
                    VLog.e("onAdDismissedFullScreenContent");
//                    if (callback != null) {
//                        callback.endSuccess();
//                    }
                    if (callback != null) {
                        callback.showAdResult(true);
                    }

                }

                @Override
                public void onAdFailedToShowFullScreenContent(@NonNull AdError adError) {
                    super.onAdFailedToShowFullScreenContent(adError);

                    //preAd(null);
//                    if (callback != null) {
//                        callback.endLoad();
//                    }
                    preAd(null);
                    Map<String, Object> map = new HashMap<>();
                    map.put("scene", scence);
                    map.put("showAdError", adError.getMessage());
                    VLog.event("Intersitial_Fail", map);
                    VLog.e("showAd fail:" + adError.getMessage());
                    if (callback != null) {
                        callback.showAdResult(false);
                    }
                }

                @Override
                public void onAdImpression() {
                    super.onAdImpression();
                }

                @Override
                public void onAdShowedFullScreenContent() {
                    //VPNApp.setInApp(true);;
                    super.onAdShowedFullScreenContent();
                    Map<String, Object> map = new HashMap<>();
                    map.put("scene", scence);
                    VLog.event("Intersitial_Show", map);
                    VLog.e("showAd success");

                }
            });
        } else {
            preAd(null);
            VLog.e("showAd == null");
            if (callback != null) {
                callback.showAdResult(false);
            }
            VLog.e("showAd == null");
        }
    }

    private void setAdPaidListener(InterstitialAd ad, String scence, UUID uuid) {
        ad.setOnPaidEventListener(new OnPaidEventListener() {
            @Override
            public void onPaidEvent(AdValue adValue) {
                String adUnitId = ad.getAdUnitId();
                AdapterResponseInfo loadedAdapterResponseInfo = ad.getResponseInfo().
                        getLoadedAdapterResponseInfo();
                Bundle extras = ad.getResponseInfo().getResponseExtras();
                AdValueUpload.adValueReport(adValue, adUnitId, loadedAdapterResponseInfo, extras, 2, scence, uuid);
            }
        });
    }


//    public void loadNativeAd(LoadAdCallback callback) {
//        callback.endLoad();
//    }

    public void preNativeAd(PreAdCallback callback) {
        final boolean isConnected = VPNPresenter.INSTANCE.isConnected();
        String adId = isConnected ? mAdConfigUtils.afterNativeAdID : mAdConfigUtils.beforeNativeAdID;
        if (TextUtils.isEmpty(adId)) {
            return;
        }
        AdLoader adLoader = new AdLoader.Builder(VPNApp.getBase(), adId)
                .forNativeAd(new NativeAd.OnNativeAdLoadedListener() {
                    @Override
                    public void onNativeAdLoaded(NativeAd nativeAd) {
                        if (isConnected) {
                            mAdConfigUtils.afterNativeAd = nativeAd;
                        } else {
                            mAdConfigUtils.beforeNativeAd = nativeAd;
                        }
                        if (callback != null) {
                            callback.load(nativeAd);
                        }
                    }
                })
                .withAdListener(new AdListener() {
                    @Override
                    public void onAdFailedToLoad(LoadAdError adError) {
                        if (isConnected) {
                            mAdConfigUtils.afterNativeAd = null;
                        } else {
                            mAdConfigUtils.beforeNativeAd = null;
                        }
                    }
                })
                .withNativeAdOptions(new NativeAdOptions.Builder()
                        .build())
                .build();
        adLoader.loadAd(new AdRequest.Builder().build());

    }

    public void loadSplashAd(final Activity activity, LoadAdCallback callback) {
        // callback.endLoad();
        if (AdSwith.hideAdSplash) {
            if (callback != null) {
                callback.endLoad(false);
                return;
            }
        }
        if (appOpenAd == null) {
            if (callback != null) {
                preSplashAd(null);
                callback.endLoad(false);
                return;
            }

        }
        AppOpenAd ad = appOpenAd;
        String scence = "Splash_Open";
        String scenceUUId = UUID.randomUUID().toString();
        Map<String, Object> map = new HashMap<>();
        map.put("scene", scence);
        VLog.event("Splash_Scene", map);
        ad.show(activity);
        VLog.e("loadSplashAd begin");
        ;
        ad.setFullScreenContentCallback(new FullScreenContentCallback() {
            @Override
            public void onAdClicked() {
                super.onAdClicked();
                Map<String, Object> map = new HashMap<>();
                map.put("scene", scence);
                VLog.event("Splash_Click", map);
            }

            @Override
            public void onAdDismissedFullScreenContent() {
                super.onAdDismissedFullScreenContent();
                //VPNApp.setInApp(true);
                preSplashAd(null);
                //loadSplashAd(activity, null);
//                if (callback != null) {
//                    callback.onDissmiss();
//                }
                if (callback != null) {
                    callback.showAdResult(true);
                }
            }

            @Override
            public void onAdFailedToShowFullScreenContent(@NonNull AdError adError) {
                super.onAdFailedToShowFullScreenContent(adError);
                VLog.e("loadSplashAd onAdFailedToShowFullScreenContent:" + adError.getMessage());
                //loadSplashAd(activity, null);
                preSplashAd(null);
//                if (splashAdShwoBack != null) {
//                    splashAdShwoBack.onFailShow();
//                }
                if (callback != null) {
                    callback.showAdResult(false);
                }
                VLog.event("SplashAd_onAdFailedToShow");
            }

            @Override
            public void onAdImpression() {
                super.onAdImpression();
            }

            @Override
            public void onAdShowedFullScreenContent() {
                //VPNApp.setInApp(true);
                super.onAdShowedFullScreenContent();
                //CustomReportManager.INSTANCE.recordEvent("SplashAd_onAdShowedFullScreenContent");
                Map<String, Object> map = new HashMap<>();
                map.put("scene", scence);
                VLog.event("Splash_Show", map);
            }
        });
    }

    private AppOpenAd appOpenAd = null;

    public void preSplashAd(PreAdCallback callback) {
        String id = VPNPresenter.INSTANCE.isConnected() ? mAdConfigUtils.afterAppOpenAdID : mAdConfigUtils.beforeAppOpenAdID;
        if (TextUtils.isEmpty(id)) {
            return;
        }
        AdRequest adRequest = new AdRequest.Builder().build();
        VLog.event("SplashAd_preSplashAd");
        VLog.e("SplashAd_beginLoad");
        ;
        AppOpenAd.load(
                VPNApp.getBase(), id, adRequest,
                AppOpenAd.APP_OPEN_AD_ORIENTATION_PORTRAIT,
                new AppOpenAd.AppOpenAdLoadCallback() {
                    @Override
                    public void onAdLoaded(@NonNull AppOpenAd ad) {
                        appOpenAd = ad;
                        VLog.event("SplashAd_preSplashAd sucess");
                        VLog.e("SplashAd_onAdLoaded");
                        ;
                        setOpenAdPaid(appOpenAd);
                        if (callback != null) {
                            callback.load(ad);
                        }
                    }

                    @Override
                    public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                        super.onAdFailedToLoad(loadAdError);
                        VLog.e("SplashAd_preSplashAd fail:" + loadAdError.getMessage());
                        VLog.event("SplashAd_onAdFailedToLoad");
                        if (callback != null) {
                            callback.fail();
                        }
                    }

                });
    }


    public interface LoadAdCallback {
        void beginLoad();

        void endLoad(boolean success);

        void showAdResult(boolean success);

    }

    public interface PreAdCallback {
        void load(Object ad);

        void fail();
    }

    public void setOpenAdPaid(AppOpenAd ad) {
        ad.setOnPaidEventListener(new OnPaidEventListener() {
            @Override
            public void onPaidEvent(AdValue adValue) {
                String adUnitId = ad.getAdUnitId();
                AdapterResponseInfo loadedAdapterResponseInfo = ad.getResponseInfo().
                        getLoadedAdapterResponseInfo();
                Bundle extras = ad.getResponseInfo().getResponseExtras();
                AdValueUpload.adValueReport(adValue, adUnitId,
                        loadedAdapterResponseInfo, extras,
                        1, "OPEN_APP", UUID.randomUUID());
            }
        });
    }


}
